//
//  HRMessageCell.m
//  SpeedDating
//
//  Created by ISU1 on 17/1/5.
//  Copyright © 2017年 isu. All rights reserved.
//

#import "HRMessageCell.h"

#define Test_Message_Font_Size 16

#define MaxWidth [UIScreen mainScreen].bounds.size.width-(10+[RCIM sharedRCIM].globalMessagePortraitSize.width+10)*2-5-35

@interface HRMessageCell ()<RCAttributedLabelDelegate>

- (void)initialize;

@property (nonatomic, strong) UIButton *textButton;

@end

@implementation HRMessageCell

+ (CGSize)sizeForMessageModel:(RCMessageModel *)model
      withCollectionViewWidth:(CGFloat)collectionViewWidth
         referenceExtraHeight:(CGFloat)extraHeight {
    HRMessage *message = (HRMessage *)model.content;
    CGSize size = [HRMessageCell getBubbleBackgroundViewSize:message];
    
    CGFloat __messagecontentview_height = size.height;
    __messagecontentview_height += extraHeight;
    
    return CGSizeMake(collectionViewWidth, __messagecontentview_height);
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self initialize];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self initialize];
    }
    return self;
}

- (void)initialize {
    self.bubbleBackgroundView = [[UIImageView alloc] initWithFrame:CGRectZero];
    [self.messageContentView addSubview:self.bubbleBackgroundView];
    
    self.textLabel = [[RCAttributedLabel alloc] initWithFrame:CGRectZero];
    [self.textLabel setFont:[UIFont systemFontOfSize:Test_Message_Font_Size]];
    
    self.textLabel.numberOfLines = 0;
    [self.textLabel setLineBreakMode:NSLineBreakByWordWrapping];
    [self.textLabel setTextAlignment:NSTextAlignmentLeft];
    [self.textLabel setTextColor:[UIColor blackColor]];
    [self.bubbleBackgroundView addSubview:self.textLabel];
    self.bubbleBackgroundView.userInteractionEnabled = YES;
    
    self.answerLabelView0 = [[UIView alloc] initWithFrame:CGRectZero];
    self.answerLabel0 = [[RCAttributedLabel alloc] initWithFrame:CGRectZero];
    self.answerLabelView1 = [[UIView alloc] initWithFrame:CGRectZero];
    self.answerLabel1 = [[RCAttributedLabel alloc] initWithFrame:CGRectZero];
    self.answerLabelView2 = [[UIView alloc] initWithFrame:CGRectZero];
    self.answerLabel2 = [[RCAttributedLabel alloc] initWithFrame:CGRectZero];
    self.answerLabelView3 = [[UIView alloc] initWithFrame:CGRectZero];
    self.answerLabel3 = [[RCAttributedLabel alloc] initWithFrame:CGRectZero];
    self.answerLabelView4 = [[UIView alloc] initWithFrame:CGRectZero];
    self.answerLabel4 = [[RCAttributedLabel alloc] initWithFrame:CGRectZero];
    self.answerLabelView5 = [[UIView alloc] initWithFrame:CGRectZero];
    self.answerLabel5 = [[RCAttributedLabel alloc] initWithFrame:CGRectZero];
    self.answerLabelView6 = [[UIView alloc] initWithFrame:CGRectZero];
    self.answerLabel6 = [[RCAttributedLabel alloc] initWithFrame:CGRectZero];
    self.answerLabelView7 = [[UIView alloc] initWithFrame:CGRectZero];
    self.answerLabel7 = [[RCAttributedLabel alloc] initWithFrame:CGRectZero];
    self.answerLabelView8 = [[UIView alloc] initWithFrame:CGRectZero];
    self.answerLabel8 = [[RCAttributedLabel alloc] initWithFrame:CGRectZero];
    self.answerLabelView9 = [[UIView alloc] initWithFrame:CGRectZero];
    self.answerLabel9 = [[RCAttributedLabel alloc] initWithFrame:CGRectZero];
    self.answerLabelArray = @[self.answerLabel0,self.answerLabel1,self.answerLabel2,self.answerLabel3,self.answerLabel4,self.answerLabel5,self.answerLabel6,self.answerLabel7,self.answerLabel8,self.answerLabel9].mutableCopy;
    self.answerLabelViewArray = @[self.answerLabelView0,self.answerLabelView1,self.answerLabelView2,self.answerLabelView3,self.answerLabelView4,self.answerLabelView5,self.answerLabelView6,self.answerLabelView7,self.answerLabelView8,self.answerLabelView9].mutableCopy;
    for (int i = 0; i < 10; i ++) {
        self.answerLabelViewArray[i].backgroundColor = TheLinColor;
        [self.bubbleBackgroundView addSubview:self.answerLabelViewArray[i]];
        [self.answerLabelArray[i] setFont:[UIFont systemFontOfSize:14]];
        self.answerLabelArray[i].numberOfLines = 0;
        [self.answerLabelArray[i] setLineBreakMode:NSLineBreakByWordWrapping];
        [self.answerLabelArray[i] setTextAlignment:NSTextAlignmentLeft];
        [self.answerLabelArray[i] setTextColor:[UIColor blackColor]];
        [self.bubbleBackgroundView addSubview:self.answerLabelArray[i]];
    }
    
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
    [self.bubbleBackgroundView addSubview:self.imageView];
    UILongPressGestureRecognizer *longPress =
    [[UILongPressGestureRecognizer alloc]
     initWithTarget:self
     action:@selector(longPressed:)];
    [self.bubbleBackgroundView addGestureRecognizer:longPress];
    
    UITapGestureRecognizer *textMessageTap = [[UITapGestureRecognizer alloc]
                                              initWithTarget:self
                                              action:@selector(tapTextMessage:)];
//    textMessageTap.numberOfTapsRequired = 1;
//    textMessageTap.numberOfTouchesRequired = 1;
    //self.textLabel.userInteractionEnabled = YES;
    [self.bubbleBackgroundView addGestureRecognizer:textMessageTap];
    //[self.textLabel addGestureRecognizer:textMessageTap];
    //[self.textLabel setDelegate:self];
}

- (void)tapTextMessage:(UIGestureRecognizer *)gestureRecognizer {
    CGPoint point = [gestureRecognizer locationInView:self.bubbleBackgroundView];
    NSLog(@"x=%f,y=%f",point.x,point.y);
    for (int i = 0; i < self.answerLabelArray.count; i ++) {
        UILabel *label = self.answerLabelArray[i];
        if (point.x>label.frame.origin.x&&point.x<label.frame.origin.x+label.frame.size.width&&point.y>label.frame.origin.y&&point.y<label.frame.origin.y+label.frame.size.height) {
            HRMessage *message = (HRMessage *)self.model.content;
            message.answer = [NSString stringWithFormat:@"%@%@",self.textLabel.text,[label.text substringWithRange:NSMakeRange(2, label.text.length-2)]];
            RCMessageModel *model = [RCMessageModel new];
            model.objectName = @"app:custom";
            model.content = message;
            if ([self.delegate respondsToSelector:@selector(didTapMessageCell:)]) {
                [self.delegate didTapMessageCell:model];
            }
        }
    }
}

- (void)setDataModel:(RCMessageModel *)model {
    [super setDataModel:model];
    
    [self setAutoLayout];
}

- (void)setAutoLayout {
    HRMessage *testMessage = (HRMessage *)self.model.content;
    if (testMessage) {
        self.textLabel.text = testMessage.ask;
        if (testMessage.img.length) {
            [self.imageView sd_setImageWithURL:[NSURL URLWithString:HttpImgUrl(testMessage.img)] placeholderImage:[UIImage imageNamed:@"llustration"]];
            //self.imageView.backgroundColor = [UIColor redColor];
        }
        NSArray *array = [testMessage.answer componentsSeparatedByString:@","];
        for (int i = 0; i < array.count; i ++) {
            self.answerLabelArray[i].text = array[i];
        }
    }
    CGSize answerLabelSize = [[self class] getAnswerLabelSize:testMessage];
    CGSize imageViewSize = [[self class] getImageViewSize:testMessage];
    CGSize textLabelSize = [[self class] getTextLabelSize:testMessage];
    CGSize bubbleBackgroundViewSize = [[self class] getBubbleSize:textLabelSize imageViewSize:imageViewSize answerLabelSize:answerLabelSize];
    CGRect messageContentViewRect = self.messageContentView.frame;
    
    //拉伸图片
    if (MessageDirection_RECEIVE == self.messageDirection) {
        NSArray *array = [testMessage.answer componentsSeparatedByString:@","];
        self.textLabel.frame =
        CGRectMake(20, 7, textLabelSize.width, textLabelSize.height);
        self.imageView.frame = CGRectMake(20, 7+5+textLabelSize.height, imageViewSize.width, imageViewSize.height);
        for (int i = 0; i < array.count; i ++) {
            CGSize labelSize = [[self class]getAnswerLabelSize:testMessage index:i];
            if (i == 0) {
                self.answerLabelArray[i].frame = CGRectMake(28, 7+5+textLabelSize.height+imageViewSize.height+10, labelSize.width, labelSize.height);
                self.answerLabelViewArray[i].frame = CGRectMake(20, 7+5+textLabelSize.height+imageViewSize.height+10, labelSize.width+16, labelSize.height);
            } else {
                CGRect labelRect = self.answerLabelArray[i-1].frame;
                self.answerLabelArray[i].frame = CGRectMake(28, labelRect.origin.y + labelRect.size.height +10, labelSize.width, labelSize.height);
                self.answerLabelViewArray[i].frame = CGRectMake(20, labelRect.origin.y + labelRect.size.height +10, labelSize.width+16, labelSize.height);
            }
        }
        messageContentViewRect.size.width = bubbleBackgroundViewSize.width;
        self.messageContentView.frame = messageContentViewRect;
        
        self.bubbleBackgroundView.frame = CGRectMake(
                                                     0, 0, bubbleBackgroundViewSize.width, bubbleBackgroundViewSize.height);
        UIImage *image = [RCKitUtility imageNamed:@"chat_from_bg_normal"
                                         ofBundle:@"RongCloud.bundle"];
        self.bubbleBackgroundView.image = [image
                                           resizableImageWithCapInsets:UIEdgeInsetsMake(image.size.height * 0.8,
                                                                                        image.size.width * 0.8,
                                                                                        image.size.height * 0.2,
                                                                                        image.size.width * 0.2)];
    } else {
        self.textLabel.frame =
        CGRectMake(12, 7, textLabelSize.width, textLabelSize.height);
        self.imageView.frame = CGRectMake(12, 7+5+textLabelSize.height, imageViewSize.width, imageViewSize.height);
        messageContentViewRect.size.width = bubbleBackgroundViewSize.width;
        messageContentViewRect.size.height = bubbleBackgroundViewSize.height;
        messageContentViewRect.origin.x =
        self.baseContentView.bounds.size.width -
        (messageContentViewRect.size.width + HeadAndContentSpacing +
         [RCIM sharedRCIM].globalMessagePortraitSize.width + 10);
        self.messageContentView.frame = messageContentViewRect;
        
        self.bubbleBackgroundView.frame = CGRectMake(
                                                     0, 0, bubbleBackgroundViewSize.width, bubbleBackgroundViewSize.height);
        UIImage *image = [RCKitUtility imageNamed:@"chat_to_bg_normal"
                                         ofBundle:@"RongCloud.bundle"];
        self.bubbleBackgroundView.image = [image
                                           resizableImageWithCapInsets:UIEdgeInsetsMake(image.size.height * 0.8,
                                                                                        image.size.width * 0.2,
                                                                                        image.size.height * 0.2,
                                                                                        image.size.width * 0.8)];
    }
}

- (void)longPressed:(id)sender {
    UILongPressGestureRecognizer *press = (UILongPressGestureRecognizer *)sender;
    if (press.state == UIGestureRecognizerStateEnded) {
        return;
    } else if (press.state == UIGestureRecognizerStateBegan) {
        [self.delegate didLongTouchMessageCell:self.model
                                        inView:self.bubbleBackgroundView];
    }
}

+ (CGSize)getAnswerLabelSize:(HRMessage *)message index:(NSInteger)index {
    NSArray *array = [message.answer componentsSeparatedByString:@","];
    float maxWidth = MaxWidth;
    CGRect textRect = [array[index]
                       boundingRectWithSize:CGSizeMake(maxWidth-16, 8000)
                       options:(NSStringDrawingTruncatesLastVisibleLine |
                                NSStringDrawingUsesLineFragmentOrigin |
                                NSStringDrawingUsesFontLeading)
                       attributes:@{
                                    NSFontAttributeName :
                                        [UIFont systemFontOfSize:14]
                                    }
                       context:nil];
    textRect.size.height = ceilf(textRect.size.height);
    textRect.size.width = ceilf(textRect.size.width);
    return CGSizeMake(maxWidth-16, textRect.size.height);
}

+ (CGSize)getAnswerLabelSize:(HRMessage *)message {
    NSArray *array = [message.answer componentsSeparatedByString:@","];
    CGSize labelSize = CGSizeZero;
    for (int i = 0; i < array.count; i ++) {
        CGSize size = [[self class] getAnswerLabelSize:message index:i];
        labelSize.height += size.height;
    }
    return CGSizeMake(MaxWidth, labelSize.height + 10*array.count);
}

+ (CGSize)getImageViewSize:(HRMessage *)message {
    if (message.img.length) {
        return CGSizeMake(MaxWidth, MaxWidth+5);
    } else {
        return CGSizeZero;
    }
}

+ (CGSize)getTextLabelSize:(HRMessage *)message {
    if ([message.ask length] > 0) {
        float maxWidth =
        [UIScreen mainScreen].bounds.size.width -
        (10 + [RCIM sharedRCIM].globalMessagePortraitSize.width + 10) * 2 - 5 -
        35;
        CGRect textRect = [message.ask
                           boundingRectWithSize:CGSizeMake(maxWidth, 8000)
                           options:(NSStringDrawingTruncatesLastVisibleLine |
                                    NSStringDrawingUsesLineFragmentOrigin |
                                    NSStringDrawingUsesFontLeading)
                           attributes:@{
                                        NSFontAttributeName :
                                            [UIFont systemFontOfSize:Test_Message_Font_Size]
                                        }
                           context:nil];
        textRect.size.height = ceilf(textRect.size.height);
        textRect.size.width = ceilf(textRect.size.width);
        return CGSizeMake(textRect.size.width + 5, textRect.size.height + 5);
    } else {
        return CGSizeZero;
    }
}

+ (CGSize)getBubbleSize:(CGSize)textLabelSize imageViewSize:(CGSize)imageViewSize answerLabelSize:(CGSize)answerLabelSize {
    CGSize bubbleSize = CGSizeZero;
    if (imageViewSize.width > 0 && textLabelSize.width < imageViewSize.width) {
        bubbleSize.width = imageViewSize.width;
    } else {
        bubbleSize.width = textLabelSize.width;
    }
    if (imageViewSize.width > 0) {
        bubbleSize.height = textLabelSize.height + imageViewSize.height + answerLabelSize.height+10;
    } else {
        bubbleSize.height = textLabelSize.height + answerLabelSize.height+10;
    }
    
    if (bubbleSize.width + 12 + 20 > MaxWidth) {
        bubbleSize.width = bubbleSize.width + 12 + 20;
    } else {
        bubbleSize.width = MaxWidth + 12 + 20;
    }
    if (bubbleSize.height + 7 + 7 > 40) {
        bubbleSize.height = bubbleSize.height + 7 + 7;
    } else {
        bubbleSize.height = 40;
    }
    
    return bubbleSize;
}

+ (CGSize)getBubbleBackgroundViewSize:(HRMessage *)message {
    CGSize textLabelSize = [[self class] getTextLabelSize:message];
    CGSize imageViewSize = [[self class] getImageViewSize:message];
    CGSize answerLabelSize = [[self class] getAnswerLabelSize:message];
    return [[self class] getBubbleSize:textLabelSize imageViewSize:imageViewSize answerLabelSize:answerLabelSize];
}

@end
